;(function($){
	$.widget("tempo.altree",{
		options:{
			expand: true,
			url: "local",
			//en_US
			langType: "zh_CN",
			data: [],
			//权限数据,id为key
			authData: {},
			authType: '3',
			param: {},
			isLeaf: function(data){
				return false;
			},
			operate: function(data){
				return true;
			},
			viewCallback: $.noop,
			isPagination: false,
			beforePaging: $.noop,
			// 同一级节点渲染限制数量，小于等于0为不限制
			nodeLimit: 0
		},
		_create: function(){
			var opts = this.options;
			this.element.addClass("tempo-app-list-tree")
			.addClass("tempo-app-list-tree-type-" + opts.authType);
			this._class = {
				header: "tempo-app-list-tree-header",
				body: "tempo-app-list-tree-body",
				footer: "tempo-app-list-tree-footer",
				pages:"pages",
				title: "tree-cell-title",
				code : "tree-cell-code",
				deptName :"tree-cell-deptname",
				progeny: "tree-cell-progeny",
				user: "tree-cell-user",
				auth: "tree-cell-auth",
				item: "tree-item",
				content: "tree-content",
				icon: "tree-icon",
				open: "tempo-ui-icon-downarrows-thin",
				close: "tempo-ui-icon-rightarrows-undertint",
				childrens: "tree-childrens",
				complete: "tree-complete",
				visit_auth: "tree-visit-auth",
				export_auth: "tree-export-auth",
				share_auth: "tree-share-auth",
				print_auth: "tree-print-auth",
				progeny_auth: "tree-progeny-auth",
				modified: "tree-modified",
				mark: "tree-mark",
				loading: "tempo-app-list-tree-loading",
				progeny_disable: "tree-progeny-disable"
			};
			this._i18n = {
				zh_CN: {
					name: "名称",
					userName:"姓名",
					userCode:"人员编码",
					deptName:"所属部门",
					progeny: "是否包含下级",
					user: "人员",
					auth: "案例权限",
					view: "查看",
					visit: "查看",
					// expor: "导出",
					share: "分享",
					print: "打印"
				},
				en_US: {
					name: "Name",
					userName:"UserName",
					userCode:"UserCode",
					deptName:"DeptName",
					progeny: "Subordinate",
					user: "User",
					auth: "Authorization",
					view: "View",
					visit: "Visit",
					// expor: "Export",
					share: "Share",
					print: "Print"
				}
			};
			$('<div class="shade">').append($('<div class="loading">')).appendTo(this.element);
			this._markDataHandle();
			this._render();
			this._initEvent();
		},
		_initEvent: function(){
			var that = this;
			var ele = this.element;
			var opts = this.options;
			var style = this._class;
			//树展开
			ele.on("click", "." + style.body + " ." + style.title, function(event){
				var icon = $(this).find("." + style.icon);
				if (!icon.hasClass("tempo-ui-icon")) {
					return
				}
				var item = $(this).parents("." + style.item);
				if (item.hasClass(style.complete)) {
					var item = $(this).parents("." + style.item);
					if (icon.hasClass(style.close)) {
						icon.removeClass(style.close).addClass(style.open);
						item.next("." + style.childrens).show();
					}else{
						icon.removeClass(style.open).addClass(style.close);
						item.next("." + style.childrens).hide();
					}
				}else{
					var nodeData = item.data("data");
					var level = parseInt(item.attr("_level"));
					icon.removeClass(style.close).addClass(style.loading);
					that._loadData({
						id: nodeData.id
					}, function(data){
						var children = $("<div>").addClass(style.childrens).show();
						if(opts.authType == "6"){
							that._renderTree(data.rows, children, level + 1, item);
						}else{
							that._renderTree(data, children, level + 1, item);
						}
						item.after(children).addClass(style.complete);
						icon.removeClass(style.loading).addClass(style.open);
					})
				}
			});
			//权限联动
			ele.on("change", "." + style.body + " input:checkbox", function(event){
				var auth = $(this).parents("." + style.auth);
				var checked = $(this).prop("checked");
				if ($(this).hasClass(style.visit_auth)) {
					auth.find("input:checkbox").prop("checked", checked);
					if (!checked) {
						$(this).parents("." + style.item).find("." + style.progeny).find("input:checkbox").prop("checked", false).change();
					}
				}else{
					if (checked) {
						auth.find("." + style.visit_auth).prop("checked", true);
					}
				}
			});
			//添加修改状态
			ele.on("change", "input:checkbox", function(event){
				var item = $(this).parents("." + style.item);
				item.addClass(style.modified);
			});
			//含下级处理
			ele.on("change", ".tree-cell-progeny input:checkbox", function(event){
				var checked = $(this).prop("checked");
				var item = $(this).parents("." + style.item);
				if (checked) {
					item.addClass(style.progeny_disable);
					item.next("." + style.childrens).find("." + style.item).addClass(style.progeny_disable);
					item.next("." + style.childrens).find("input").attr("disabled", true);
				} else {
					item.removeClass(style.progeny_disable);
					item.next("." + style.childrens).find("." + style.item).removeClass(style.progeny_disable);
					item.next("." + style.childrens).find("input").removeAttr("disabled");
				}
			});
			ele.on("click", ".tree-cell-user label", function(event){
				var item = $(this).parents("." + style.item);
                // var item = $("body");
				opts.viewCallback.call(that, item.data("data"));
			});
		},
		_render: function(){
			var options = this.options;
			var style = this._class;
			var header = this._buildHeader();
			var content = $("<div>").addClass(style.body);
			if (options.url == "local") {
				this._renderTree(options.data, content, 1, $());
				this.element.append(header).append(content).append($("<div>").addClass(style.footer));;
				if (options.expand) {
					this.element.find("." + style.body + "> ." + style.item + " ." + style.title).trigger("click");
				}
			} else {
				this._loadData(options.param, function(data){
					this._renderTree(options.isPagination ? data.rows : data, content, 1, $());
					this.element.append(header).append(content).append($("<div>").addClass(style.footer));
					if (options.isPagination) {
						this._renderPagination(data);
					}
					if (options.expand) {
						this.element.find("." + style.body + "> ." + style.item + " ." + style.title).trigger("click");
					}
				})
			}

		},
		_buildHeader: function(){
			var options = this.options;
			var style = this._class;
			var i18n = this._i18n[options.langType];
			var header = $("<div>").addClass(style.header);
			var content = $("<div>").addClass(style.content).appendTo(header);
			var title = $("<span>").text(i18n.name).addClass(style.title).appendTo(content);
			if (options.authType == "3") {
				$("<span>").text(i18n.progeny).addClass(style.progeny).appendTo(content);
			}
			if (options.authType != "6") {
				$("<span>").text(i18n.user).addClass(style.user).appendTo(content);
			}
			if(options.authType == '6'){
				title.text(i18n.userName);
				$("<span>").text(i18n.userCode).addClass(style.code).appendTo(content);
				$("<span>").text(i18n.deptName).addClass(style.deptName).appendTo(content);
			}
			var auth = $("<span>").text(i18n.auth).addClass(style.auth).appendTo(content);
			return header;
		},
		_renderPagination: function(data){
			var that = this;
			var style = this._class;
			var options = this.options;
			var pagebar = $('<div id="Pagination"></div>' +
				'<div class="searchPage">' +
		          '<span class="page-sum">共<strong class="allPage">'+ ((data.totalPages || data.total) || 0) +'</strong>页</span>' +
		          '<span class="page-go">跳转<input type="text" name="page">页</span>' +
		          '<a href="javascript:;" class="page-btn">GO</a>' +
		        '</div>' +
	        '</div>');
			this.element.find("." + style.footer).empty().addClass("pages").append(pagebar);
			pagebar.first().pagination((data.totalPages || data.total), {
				callback:function(e){
					options.beforePaging.call(that, arguments);
					options.param.page = e + 1;
					that._loadData(options.param, function(data){
						that._renderTree(data.rows, that.element.find("." + style.body).empty(), 1, $());
					})
				}
			});
		},
		_renderTree: function(data, parent, level, pNode){
			var style = this._class;
			var opts = this.options;
			if(!data || data.length == 0){
				return;
			}
			var tempDom = $("<div>");
			for (var i = 0; i < data.length; i++) {
				if (opts.nodeLimit > 0 && i >= opts.nodeLimit) {
					break;
				}
				var item = data[i];
				var treeItem = this._buildItem(item, level);
				//填充数据
				this._fillData(treeItem, opts.authData[item.id]);
				this._markNode(treeItem);
				tempDom.append(treeItem);
				// 添加下级禁用状态
				if(pNode.hasClass(style.progeny_disable)){
					treeItem.addClass(style.progeny_disable);
					treeItem.find("input").attr("disabled", true);
				}
				if(item.children){
					var childrens = $("<div>").addClass(style.childrens).appendTo(tempDom);
					this._renderTree(item.children,childrens,level + 1, treeItem);
					treeItem.addClass(style.complete);
				}
			}
			parent.append(tempDom.children());
		},
		_buildItem: function(data, level){
			var options = this.options;
			var style = this._class;
			var i18n = this._i18n[options.langType];
			var item = $("<div>").addClass(style.item).data("data", data).attr("_level", level).attr("_id", data.id);
			var content = $("<div>").addClass(style.content).appendTo(item);
			var title = $("<div>").addClass(style.title).appendTo(content);
			var icon = $("<div>").addClass(style.icon).appendTo(title).css("margin-left", 16 * level);
			if (!options.isLeaf.call(this, data)) {
				icon.addClass("ui-icon tempo-ui-icon "+ style.close);
			}
			var label = $("<label>").text(data.name).css("width", "calc(100% - " + (16 * level + 16 + 6) + "px)").attr('title', data.name).appendTo(title);
			if (options.authType == "6") {
				$("<div>").addClass(style.code).append($("<label>").text(data.code).attr('title', data.code)).appendTo(content);
				$("<div>").addClass(style.deptName).append($("<label>").text(data.deptName).attr('title', data.deptName)).appendTo(content);
			}
			var isOperate = options.operate.call(this, data);
			if (options.authType == '3') {
				var progeny = $("<div>").addClass(style.progeny).appendTo(content);
				if (isOperate) {
					var id = TempoUtils.uuid();
					$("<input>").attr("type", "checkbox").attr("id", id).addClass("tempo-checkbox " + style.progeny_auth).appendTo(progeny);
					$("<label>").attr("for", id).appendTo(progeny);
				}
			}
			var user;
			if(options.authType != "6"){
				user = $("<div>").addClass(style.user).appendTo(content);
			}
			var auth = $("<div>").addClass(style.auth).appendTo(content);
			if (isOperate) {
				if (user && data.isOtherOrg !== true) {
					user.append($("<label>").text(i18n.view));
				}
				var visit = $("<div>").appendTo(auth);
				var uuid = TempoUtils.uuid();
				$("<input>").attr("type", "checkbox").attr("id", uuid).addClass("tempo-checkbox " + style.visit_auth).appendTo(visit);
				$("<label>").attr("for", uuid).appendTo(visit);
				// var expor = $("<div>").appendTo(auth);
				// uuid = TempoUtils.uuid();
				// $("<input>").attr("type", "checkbox").attr("id", uuid).addClass("tempo-checkbox " + style.export_auth).appendTo(expor);
				// $("<label>").text(i18n.expor).attr("for", uuid).appendTo(expor);

				// var share = $("<div>").appendTo(auth);
				// uuid = TempoUtils.uuid();
				// $("<input>").attr("type", "checkbox").attr("id", uuid).addClass("tempo-checkbox " + style.share_auth).appendTo(share);
				// $("<label>").text(i18n.share).attr("for", uuid).appendTo(share);

				var print = $("<div>").appendTo(auth);
				uuid = TempoUtils.uuid();
				$("<input>").attr("type", "checkbox").attr("id", uuid).addClass("tempo-checkbox " + style.print_auth).appendTo(print);
				$("<label>").text(i18n.print).attr("for", uuid).appendTo(print);
			}
			return item;
		},
		_fillData: function(node, data){
			if (!data) {
				return
			}
			var style = this._class;
			if (data.hasProgeny == "1") {
				node.find("." + style.progeny_auth).prop("checked", true);
				node.addClass(style.progeny_disable);
			}
			if (data.visitAuth == "1") {
				node.find("." + style.visit_auth).prop("checked", true);
			}
			if (data.shareAuth == "1") {
				node.find("." + style.share_auth).prop("checked", true);
			}
			if (data.exportAuth == "1") {
				node.find("." + style.export_auth).prop("checked", true);
			}
			if (data.printAuth == "1") {
				node.find("." + style.print_auth).prop("checked", true);
			}
		},
		_markDataHandle: function(){
			var opts = this.options;
			var authData = opts.authData;
			var dLevelCodes = [];
			for (var i in authData) {
				if (authData[i]) {
					dLevelCodes.push(authData[i].dLevelCode);
				}
			}
			this._dLevelCodes = dLevelCodes;
		},
		_markNode: function(node){
			var opts = this.options;
			var style = this._class;
			var nodeData = node.data("data");
			var dLevelCode = nodeData.dLevelCode;
			if (dLevelCode) {
				var codes = this._dLevelCodes;
				for (var i = 0; i < codes.length; i++) {
					if (codes[i].indexOf(dLevelCode) == 0) {
						if (opts.authType == '3' && codes[i].length == dLevelCode.length) {
							continue;
						}
						node.find("." + style.title).addClass(style.mark);
						break;
					}
				}
			}
		},
		_getItemAuth: function(node){
			var style = this._class;
			var opts = this.options;
			var auth = {
				objId: node.attr("_id"),
				objType: opts.authType,
				dLevelCode: node.data("data").dLevelCode,
				hasProgeny: node.find("." + style.progeny_auth).prop("checked") ? "1" : "0",
				visitAuth: node.find("." + style.visit_auth).prop("checked") ? "1" : "0"
				// shareAuth: node.find("." + style.share_auth).prop("checked") ? "1" : "0",
				// exportAuth: node.find("." + style.export_auth).prop("checked") ? "1" : "0",
				// printAuth: node.find("." + style.print_auth).prop("checked") ? "1" : "0"
			};
			if (opts.authType != "3") {
				auth.hasProgeny = null;
			}
			if (auth.dLevelCode) {
				auth.dLevelCode = auth.dLevelCode.replace("------", "");
			}
			return auth;
		},
		getModifiedAuths: function(){
			var that = this;
			var opts = this.options;
			var ele = this.element;
			var style = this._class;
			var authData = opts.authData;

			var auths = [];
			var items = ele.find("." + style.modified);
			items.each(function(index, ele){
				var auth = that._getItemAuth($(ele));
				auths.push(auth);
				$(ele).removeClass(style.modified);
//				var id = $(ele).attr("_id");
//				var data = authData[id];
//				if (data) {
//					//历史有
//					if (!(data.hasProgeny == auth.hasProgeny && data.visitAuth == auth.visitAuth
//							&& data.shareAuth == auth.shareAuth && data.exportAuth == auth.exportAuth
//							&& data.printAuth == auth.printAuth)) {
//						auths.push(auth);
//					}
//				}else{
//					//历史没有
//					if (auth.visitAuth == "1") {
//						auths.push(auth);
//					}
//				}
			});
			return auths;
		},
		_loadData: function(param, callback){
			var that = this;
			var opts = this.options;
			$(this.element).find('.shade').show();
			$.ajax({
				url: opts.url,
				data: param,
				type:'post',
				complete: function(XMLHttpRequest, textStatus){
					$(that.element).find('.shade').hide();
				},
				success:function(resultData){
					if(resultData.success){
						var data = resultData.data;
						if (opts.authType == "6") {
							data = resultData.data;
						}
						callback.call(that, data);
					}else{
						console.log(resultData.success);
						callback.call(that, []);
					}
				}
			});
		},
		_destroy: function(){
			var ele = this.element;
			ele.off();
			this._super();
			return this;
		}
	})
})(jQuery)
